package org.fastsyncer.common.util;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public abstract class JsonUtil {

	private static final ObjectMapper mapper = new ObjectMapper();

	public static String objToJson(Object obj) {
		try {
			// 将对象转换成json
			return mapper.writeValueAsString(obj);
		} catch (JsonGenerationException e) {
		} catch (JsonMappingException e) {
		} catch (IOException e) {
		}
		return null;
	}

	public static <T> T jsonToObj(String json, Class<T> valueType) {
		try {
			return (T) mapper.readValue(json, valueType);
		} catch (Exception e) {
		}
		return null;
	}
	
	public static String jsonToString(String json) {
		if(null == json){
			return null;
		}
		// 判断是否满足JSON格式
		if(json.startsWith("\"") && json.endsWith("\"")){
			try {
				json = mapper.readValue(json, String.class);
			} catch (Exception e) {
			}
		}
		return json;
	}

}
